package com.example.springboot_demo.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

// CGLIB代理拦截器
class MyMethodCglibInterceptor implements MethodInterceptor {
    private static final Map<Class<?>, Object> PROXY_CACHE = new HashMap<>();
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("CGLIB代理前处理");
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("CGLIB代理后处理");
        return result;
    }

    // 创建代理对象的工具方法
    public static <T> T createProxy(Class<T> clazz) {
        if (!PROXY_CACHE.containsKey(clazz)) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(clazz);
            enhancer.setCallback(new MyMethodCglibInterceptor());
            Object obj=enhancer.create();
            PROXY_CACHE.put(clazz, obj);
            return (T)obj;
        }
        else {
            return (T) PROXY_CACHE.get(clazz);
        }
    }
}